import {login, logout, getInfo} from '@/api/user/index.js'
import stroage from '@/utils/storage.js'
import storage from "@/utils/storage";

const user = {
    state: {
        username: '', nickname: '', token: '', roles: [], permissions: []
    }, getters: {
        isLogin(state) {
            return state.username !== '' && state.token !== '';
        },permissions(state){
            return state.permissions
        },roles(state){
            return state.roles
        }
    }, mutations: {
        SAVE_USER(state, username) {
            state.username = username;
        }, SAVE_NIKENAME(state, nickname) {
            state.nickname = nickname;
        }, SAVE_TOKEN(state, token) {
            state.token = token;
        }, SAVE_ROLES(state, roles) {
            state.roles = roles;
        }, SAVE_PREMISSIONS(state, permissions) {
            state.permissions = permissions;
        }

    }, actions: {
        LOGIN({commit}, user) {
            return new Promise(function (resolve) {
                login(user).then(res => {
                    console.log(res.data.khUser.userName)
                    //需要将获取的数据保存起来
                    commit("SAVE_USER", res.data.khUser.userName);
                    commit("SAVE_NIKENAME", res.data.khUser.nickName);
                    commit("SAVE_TOKEN", res.data.token);
                    stroage.saveSessionObject("loginUser", res.data);
                    resolve(res);
                })
            });

        }, GIT_INFO({commit}) {
            return new Promise(resolve => {
                getInfo().then(res => {
                    commit("SAVE_ROLES", res.data.roles);
                    commit("SAVE_PREMISSIONS", res.data.prems);
                    resolve();
                })
            });

        }, LOGOUT({commit}) {
            return new Promise(function (resolve) {
                logout().then(res => {
                    //需要将获取的数据保存起来
                    commit("SAVE_USER", '');
                    commit("SAVE_NIKENAME", '');
                    commit("SAVE_TOKEN", '');
                    stroage.remove("loginUser");
                    resolve(res);
                })
            });
        }, RECOVERY_USER: function ({commit}) {
            //从storage中获取数据
            let loginUser = storage.getSessionObject("loginUser");
            if (loginUser) {
                commit("SAVE_USER", loginUser.khUser.userName);
                commit("SAVE_NIKENAME", loginUser.khUser.nickName);
                commit("SAVE_TOKEN", loginUser.token);
            }
        }
    }
}

export default user